#!/bin/bash
#
# Pulley GPG interface routines
#
# Author:   Dr. Mike Murphy (mmurphy2@coastal.edu)
# Revision: 13 November 2013
#
#   Copyright 2013 Coastal Carolina University
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.


## psec_gpg_verify <path> <signature file> <target file>
##
## Checks the signature of a file using an external signature file, returning
## 0 if the signature is valid, non-zero otherwise.
##
## <path>            Pulley GPG home directory
## <signature file>  External signature file
## <target file>     File to be validated with the signature file
##
function psec_gpg_verify_signature() {
	gpg --homedir "$1" --quiet --batch --verify "$2" "$3"
	return $?
}


## psec_gpg_import_key <path> <key file>
##
## Imports a GPG key from <key file> into the specified <path>, which is
## the GPG home directory.
##
function psec_gpg_import_key() {
	gpg --homedir "$1" --batch --import "$2"
	return $?
}


## psec_gpg_export_key <path> <output file> [keyid]
##
## Exports a public key from the key store.
##
## <path>         GPG home directory containing the key
## <output file>  Output file where the key will be written
## [keyid]        ID of the key to be exported (default key if omitted)
##
function psec_gpg_export_key() {
	gpg --homedir "$1" --batch --armor --export $3 > "$2"
	return $?
}


## psec_gpg_generate_key <path> [expert options]
##
## Generates a new GPG key.
##
## <path>            GPG home directory where key will be created
## [expert options]  Expert key generation options passed to gpg(1)
##
function psec_gpg_generate_key() {
	gpg --homedir "$1" --gen-key "$@"
	return $?
}


## psec_gpg_sign <path> <output file> <input file> [gpg opts]
##
## Generates a cryptographic signature for a given input file, writing
## the signature to a specified output file.
##
## <path>          GPG home directory containing the keys
## <output file>   Output file where the signature will be written
## <input file>    Input file for which the signature is generated
## [gpg opts]      Other options to gpg(1)
##
function psec_gpg_sign() {
	local homedir="$1"
	shift
	local outfile="$2"
	shift
	local infile="$3"
	shift
	gpg --homedir "${homedir}" --armor --quiet --output "${outfile}" \
		--detach-sig "$@" "${infile}"
	#
	return $?
}
